<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="80%"
      align-center
      :show-close="false"
      @open="handleOpen"
      @close="handleClose"
      draggable
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>{{ title }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>
      <!-- 基本信息 -->
      <div class="bg-white mt-[10px]">
        <BaseHead>基本信息</BaseHead>
        <div class="p-[10px]">
          <el-form :model="editForm" :rules="rules" label-width="130px" ref="editFormRef">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="专著名称" prop="name">
                  <el-input
                    placeholder="专著名称"
                    clearable
                    v-model="editForm.name"
                    style="width: 40%"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="拟出版日期" prop="publishDate">
                  <el-date-picker
                    v-model="editForm.publishDate"
                    type="date"
                    clearable
                    placeholder="请选择时间"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出版社" prop="publishCompany">
                  <el-input placeholder="出版社" clearable v-model="editForm.publishCompany">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属单位" prop="publishUnit">
                  <CommonTreeSelect
                    v-model="editForm.publishUnit"
                    valueKey="codeColumn"
                    labelKey="valueColumn"
                    paramsName="成果归属单位"
                    placeholder="请选择所属单位"
                    :disabled="verifyRoleType.isKyry()"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="承诺书上传" prop="fileId">
                  <FileUpload
                    :uploadUrl="uploadUrl"
                    v-model="fileList"
                    @change="fileChange"
                    :limit="1"
                    exceedLimitType="disabled"
                    tip="附件大小不超过20M"
                    class="flex-1"
                  >
                    <el-link
                      class="ml-[30px]"
                      type="primary"
                      @click="handleDownTpl('承诺书和署名知情书.docx')"
                      >模板下载</el-link
                    >
                  </FileUpload>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="一级学科" prop="subjectId">
                  <CommonSelect
                    :isFetch="false"
                    :dataList="firstSubjectList.value"
                    v-model="editForm.subjectId"
                    labelKey="label"
                    placeholder="一级学科"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="bg-white mt-[10px]">
        <BaseHead style="border-bottom: 0">
          作者信息 <el-button @click="handleAdd">添加</el-button></BaseHead
        >
        <el-table :data="memberList" class="w-full" border stripe>
          <el-table-column type="index" label="序号" width="60px" />
          <el-table-column label="作者类型">
            <template #default="{ row }">
              <div class="flex items-center">
                <span class="no-empty-icon">*</span>
                <CommonSelect
                  :isFetch="false"
                  :dataList="memberTypeList.value"
                  v-model="row.authorType"
                  valueKey="code"
                  @change="memberTypeChange(row, $event)"
                  :disabled="row.orderId == 1"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="作者姓名">
            <template #default="{ row }">
              <div class="flex items-center">
                <span class="no-empty-icon">*</span>
                <el-autocomplete
                  v-model="row.authorName"
                  :fetch-suggestions="personSearch(row)"
                  clearable
                  value-key="name"
                  highlight-first-item
                  @select="selectPerson(row, $event)"
                  @blur="selectPerosnBlur(row, $event)"
                  v-if="row.authorType != 3"
                  :disabled="row.orderId == 1"
                >
                  <template #default="{ item }">
                    <span>{{ item.name }}</span>
                    <span class="mx-[10px]">{{ item.account }}</span>
                    <span>{{ item.unitName }}</span>
                  </template>
                </el-autocomplete>
                <el-input clearable v-model="row.authorName" v-else />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="学历">
            <template #default="{ row }">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="educationList.value"
                v-model="row.eduLevelId"
                valueKey="code"
                labelKey="name"
              />
            </template>
          </el-table-column>
          <el-table-column label="职称">
            <template #default="{ row }">
              <CommonSelect
                :isFetch="false"
                :dataList="applierTitleList.value"
                v-model="row.titleId"
                labelKey="label"
              />
            </template>
          </el-table-column>
          <el-table-column label="角色类型">
            <template #default="{ row }">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="roleTypeList.value"
                v-model="row.roleType"
                valueKey="code"
                labelKey="name"
              />
            </template>
          </el-table-column>
          <el-table-column label="工作单位">
            <template #default="{ row }">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="unitList.value"
                v-model="row.authorUnitId"
                valueKey="codeColumn"
                labelKey="valueColumn"
                v-if="row.authorType != 3"
                :disabled="row.orderId == 1"
              />
              <el-input clearable v-model="row.authorUnit" v-else />
            </template>
          </el-table-column>
          <el-table-column label="备注">
            <template #default="{ row }">
              <el-input clearable v-model="row.note" />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                plain
                @click="handleDel($index)"
                v-if="row.orderId != 1"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button
              type="primary"
              @click="save(-1)"
              :loading="loading && submitType == -1"
              :disabled="loading && submitType != -1"
              >{{ verifyRoleType.isKyry() ? "暂存" : "保存" }}</el-button
            >
            <el-button
              type="primary"
              @click="save(1)"
              :loading="loading && submitType == 1"
              :disabled="loading && submitType != 1"
              v-if="verifyRoleType.isKyry()"
              >提交</el-button
            >
            <el-button
              type="primary"
              @click="save(2)"
              :loading="loading && submitType == 2"
              :disabled="loading && submitType != 2"
              v-if="
                verifyRoleType.iskycgly() &&
                ([-1, 3].includes(Number(checkStatus)) || editForm.isAuditor)
              "
              >保存并通过</el-button
            >
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import { addRecords, editRecords, recordsDetail } from "@/api/kycx";
import { getPersonList } from "@/api/project/common";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonTreeSelect from "@/views/project/components/CommonTreeSelect.vue";
import FileUpload from "@/views/project/components/FileUpload.vue";
import { ElMessage } from "element-plus";
import { assignObj, verifyRoleType, handleDownTpl } from "@/utils/main";
import useCommonFetch from "@/hooks/useCommonFetch";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const dialogVisible = ref(false);
const editFormRef = ref();
const operateId = ref(null);
const detailData = ref(null);
const memberList = ref([]);
const loading = ref(false);
const submitType = ref(null);
const title = computed(() => {
  return operateId.value ? "科研诚信-著作编辑" : "科研诚信-著作登记";
});
const uploadUrl = `/commonFile/uploadFile?modelName=科研诚信著作`;
const fileList = ref([]);
const firstSubjectList = ref([]); //一级学科
const memberTypeList = ref([]);
const educationList = ref([]); //学历
const applierTitleList = ref([]); //职称
const roleTypeList = ref([]); //角色类型
const unitList = ref([]);
const checkStatus = ref("");
//基本信息表单
const editForm = reactive({
  type: 3,
  name: "",
  publishDate: "",
  publishCompany: "",
  publishUnit: "",
  fileId: "",
  subjectId: "",
  taskId: "",
  isAuditor: "",
});
//表单验证规则
const rules = reactive({
  name: [
    {
      required: true,
      message: "专著名称必填",
    },
  ],
  fileId: [
    {
      required: true,
      message: "请上传承诺书",
    },
  ],
});
//初始化一个项目成员 用于添加
const initMemberItem = () => {
  return {
    authorType: memberTypeList.value.value[0].code, //成员类型
    authorName: "", //成员姓名
    personId: "", //成员id
    eduLevelId: "", //学历
    titleId: "", //职称
    roleType: "", //角色类型
    authorUnitId: "", //单位Id
    authorUnit: "", //单位名称
    note: "",
    authorAccount: "", //工号
    sexId: "", //性别
  };
};
//获取数据详情
const getDetail = async () => {
  try {
    const res = await recordsDetail(operateId.value, 3);
    detailData.value = res.data;
    memberList.value = res.data.authorList;
    checkStatus.value = res.data.checkstatus;
    if (res.data.fileId) {
      fileList.value = [
        {
          id: res.data.fileId,
          name: res.data.fileName,
        },
      ];
    }
  } catch (error) {
    console.log(error);
  }
};
// 新增
const add = async () => {
  operateId.value = null;
  const res = await getPersonList({ id: userStore.userRealId });
  const person = res.data[0];
  editForm.publishUnit = person.unitId;
  //默认添加当前登录人为作者
  memberList.value = [
    {
      authorType: "1", //默认为教师类型
      authorName: person.name,
      personId: person.id,
      eduLevelId: person.eduLevelId,
      titleId: person.titleId,
      roleType: "",
      authorUnitId: person.unitId,
      authorUnit: person.unitName,
      note: "",
      authorAccount: person.account,
      sexId: person.sexId,
      orderId: 1,
    },
  ];
  dialogVisible.value = true;
};
// 编辑
const edit = async (id, isAuditor, taskId) => {
  operateId.value = id;
  dialogVisible.value = true;
  await getDetail();
  nextTick(() => {
    assignObj(editForm, detailData.value);
    editForm.isAuditor = isAuditor;
    editForm.taskId = taskId;
  });
};
defineExpose({ add, edit });

//点击添加按钮
const handleAdd = () => {
  memberList.value.push(Object.assign({}, initMemberItem()));
};
//点击删除按钮删除一行
const handleDel = (index) => {
  memberList.value.splice(index, 1);
};
const emit = defineEmits(["save-success"]);
//搜索人员列表
const personSearch = (row) => {
  return async (queryString, cb) => {
    if (queryString.trim() == "") {
      return;
    }
    row.personId = "";
    const params = {
      name: queryString,
    };
    try {
      const res = await getPersonList(params);
      cb(res.data);
    } catch (error) {
      console.log(error);
    }
  };
};
//重置成员数据
const resetPerosn = (row) => {
  row.authorName = "";
  row.personId = "";
  row.eduLevelId = "";
  row.titleId = "";
  row.authorUnitId = "";
  row.authorUnit = "";
  row.authorAccount = "";
  row.sexId = "";
};
const selectPerosnBlur = (row) => {
  if (!row.personId) {
    resetPerosn(row);
  }
};
//选择项目成员改变
const selectPerson = (row, val) => {
  //判断所选成员是否已存在
  let existFlag = false;
  memberList.value.forEach((item) => {
    if (item.personId == val.id) {
      existFlag = true;
    }
  });
  if (existFlag) {
    ElMessage({
      message: "所选人员已存在！",
      type: "error",
    });
    resetPerosn(row);
    return;
  }
  row.personId = val.id;
  row.eduLevelId = val.eduLevelId;
  row.titleId = val.titleId;
  row.authorUnitId = val.unitId;
  row.authorUnit = val.unitName;
  row.authorAccount = val.account;
  row.sexId = val.sexId;
};
//选择的成员类型改变
const memberTypeChange = (row, val) => {
  //选择校外时或者从校外选择校内或学生时 清空成员信息
  if (val == 3 || (val != 3 && row.personId == "")) {
    resetPerosn(row);
  }
};
//上传附件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  editForm.fileId = ids.join(",");
};
//点击保存
const save = async (type) => {
  submitType.value = type;
  try {
    await editFormRef.value?.validate(async (valid) => {
      if (valid) {
        let fieldFlag = true;
        memberList.value.forEach((item, index) => {
          item.orderId = index + 1;
          if (!item.authorName) {
            fieldFlag = false;
          }
        });
        //校验必填字段是否全部填写
        if (!fieldFlag) {
          ElMessage({
            message: "请检查各项必填字段是否全部填写！",
            type: "error",
          });
          return;
        }
        let res;
        let params = {
          ...editForm,
          submitType: type,
          authorList: memberList.value,
        };
        loading.value = true;
        if (operateId.value) {
          params.id = operateId.value;
          res = await editRecords(params);
        } else {
          res = await addRecords(params);
        }
        if (res.code === 200) {
          ElMessage({
            message: "操作成功！",
            type: "success",
          });
          dialogVisible.value = false;
          emit("save-success");
        }
      }
    });
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
const handleOpen = () => {
  firstSubjectList.value = useCommonFetch("一级学科");
  memberTypeList.value = useCommonFetch("成员类型");
  educationList.value = useCommonFetch("学历");
  applierTitleList.value = useCommonFetch("职称");
  roleTypeList.value = useCommonFetch("承担角色-著作");
  unitList.value = useCommonFetch("成果归属单位");
};
//关闭弹窗
const handleClose = () => {
  editFormRef.value.resetFields();
  editForm.taskId = "";
  editForm.isAuditor = "";
  fileList.value = [];
  memberList.value = [];
  checkStatus.value = "";
};
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
</style>
